import React from 'react';
import {inject, observer} from 'mobx-react';
import {Modal, message,Button} from 'antd';
import * as Util from '../../../util/Util.js';
import {
  WeaDatePicker,
  WeaTextarea,
  WeaInputNumber,
  WeaSearchGroup,
  WeaFormItem,
  WeaInput,
  WeaNewScroll,
  WeaLocaleProvider
} from 'ecCom';
const toJS = mobx.toJS;
const getLabel = WeaLocaleProvider.getLabel;
@inject ('planReportViewStore')
@observer
export default class PlanSummaryModal extends React.Component {
  constructor (props) {
    super (props);
    this.state = {
      _height: Util.getCurrentHeight (),
      formValue: {
        id: 'temp+' + new Date ().getTime (),
      },
    };
    this.store = this.props.planReportViewStore;
  }

  componentWillReceiveProps (nextProps) {}

  setFormValueId = () => {
    let {formValue} = this.state;
    formValue['id'] = 'temp+' + new Date ().getTime ();
    this.setState (formValue);
  };

  resetFileds = () => {
    this.setState ({
      formValue: {
        id: 'temp+' + new Date ().getTime (),
      },
    });
    this.store.planSummaryModal.editData = {};
  };

  handleOk = () => {
    if (!this.checkMust ()) {
      message.info (getLabel('509065','请输入必填项') );
      return;
    }

    let {formValue} = this.state;
    if (formValue.undefined != '' || formValue.undefined == 0) {
      delete formValue.undefined;
      this.setState ({formValue});
    }
    //如果是编辑 
    if (this.store.planSummaryModal.edit) {
      this.store.planSummaryModal.type == 'summary'
        ? this.updateDataFromArray (
            this.store.resData.summaryout,
            this.state.formValue
          )
        : this.updateDataFromArray (
            this.store.resData.planlist,
            this.state.formValue
          );
    //如果是新增就加到列表里
    } else {
      if(this.store.planSummaryModal.rowIndex>-1){
        this.store.planSummaryModal.type == 'summary'
        // ? this.store.resData.summaryout.push (this.state.formValue)
        // : this.store.resData.planlist.push (this.state.formValue);
        //新增一行增加到当前行下面
        ? this.store.resData.summaryout.splice (this.store.planSummaryModal.rowIndex+1,0,this.state.formValue)
        : this.store.resData.planlist.splice (this.store.planSummaryModal.rowIndex+1,0,this.state.formValue);
      }else{
        this.store.planSummaryModal.type == 'summary'
        ? this.store.resData.summaryout.push (this.state.formValue)
        : this.store.resData.planlist.push (this.state.formValue);
      }

    }

    this.handleCancel ();
    this.setFormValueId ();
    // this.store.saveOrSubmitPlan ('save');
  };

  //检查必填项
  checkMust = () => {
    let {formValue} = this.state;
    var flag = true;
    let {planmap, summarymap} = this.store.resData;
    let checkMap = this.store.planSummaryModal.type == 'summary'
      ? summarymap.list
      : planmap.list;
    for (var v in formValue) {
      checkMap.map (p => {
        
        if (p['ismust'] == 1 && (formValue[p['fieldname']]==='' ||formValue[p['fieldname']]==undefined )) {
          flag = false;
        }
        if(!formValue['name'] || formValue['name']==undefined || formValue['name']==''){
          flag=false;
        }


      });
    }

    return flag;
  };

  updateDataFromArray (array, formValue) {
    let index = -1;
    array.map ((v, i) => {
      if (v.id == formValue.id) {
        index = i;
      }
    });
    if (index > -1) {
      array[index] = formValue;
      //    array.splice(index, 1);
    } else {
      array.push (formValue);
    }
  }

  handleCancel = () => {
    this.store.planSummaryModal.planSummaryModalVisible = false;
    this.resetFileds ();
  };

  onInputChange = (fieldname, e) => {
    let {formValue} = this.state;

    let col, tip = ''; //被改变的值
    let days = 0;
    let flag = true;
    if (
      fieldname == 'begindate2' &&
      formValue['enddate2'] &&
      formValue['enddate2'] != ''
    ) {
      days = Util.DateDiffDays (e, formValue['enddate2']);
      if (days < 0) {
        flag = false;
        tip = getLabel('509026','实际开始日期不能大于实际结束日期!') ;
      } else {
        col = 'days2';
      }
    } else if (
      fieldname == 'enddate2' &&
      formValue['begindate2'] &&
      formValue['begindate2'] != ''
    ) {
      days = Util.DateDiffDays (formValue['begindate2'], e);
      if (days < 0) {
        flag = false;
        tip = getLabel('509027','实际结束日期不能小于实际开始日期!') ;
      } else {
        col = 'days2';
      }
    } else if (
      fieldname == 'begindate1' &&
      formValue['enddate1'] &&
      formValue['enddate1'] != ''
    ) {
      days = Util.DateDiffDays (e, formValue['enddate1']);
      if (days < 0) {
        flag = false;
        tip = getLabel('509028','计划开始日期不能大于计划结束日期!') ;
      } else {
        col = 'days1';
      }
    } else if (
      fieldname == 'enddate1' &&
      formValue['begindate1'] &&
      formValue['begindate1'] != ''
    ) {
      days = Util.DateDiffDays (formValue['begindate1'], e);
      if (days < 0) {
        flag = false;
        tip = getLabel('509029','计划结束日期不能小于计划开始日期!') ;
      } else {
        col = 'days1';
      }
    }
    if (col != '') {
      formValue[col] = days?days:0;
      formValue["s_"+col] =  days?days:0;
    }
    if (flag) {
      if((fieldname == 'days1' || fieldname == 'days2') && !e){
        formValue[fieldname]=''
        formValue["s_"+fieldname]=''
      }else{
        formValue[fieldname] = e;
        formValue["s_"+fieldname] = typeof(e) == 'string'? e.replace(/\n/g,"<br/>"):e;
      }
      this.setState ({formValue});
    } else {
      message.info (tip);
      this.setState ({formValue});
    }
  };

  getFormItem = (type, label, value, viewAttr, fieldname, ismust, ismust2) => {
    if (viewAttr == 2 && (ismust == 1 || ismust2 == 1)) {
      viewAttr = 3;
    }
    if(fieldname=='name'){
      viewAttr=3
    }
    return (
      <WeaFormItem ecId={`${this && this.props && this.props.ecId || ''}_WeaFormItem@6edgyr`}
        label={label}
        labelCol={{span: 6}}
        wrapperCol={{span: 18}}
      >

        {type == 1 &&
          <WeaInput ecId={`${this && this.props && this.props.ecId || ''}_WeaInput@lx31fj`}
            value={value}
            viewAttr={viewAttr}
            onChange={e => this.onInputChange (fieldname, e)}
          />}
        {type == 2 &&
          <WeaTextarea ecId={`${this && this.props && this.props.ecId || ''}_WeaTextarea@8nv072`}
            viewAttr={viewAttr}
            value={value &&value.replace(/<br\/>/g, "\n")}
            onChange={e => this.onInputChange (fieldname, e)}
          />}
        {type == 3 &&
          <WeaDatePicker ecId={`${this && this.props && this.props.ecId || ''}_WeaDatePicker@d7fm3u`}
            value={value}
            viewAttr={viewAttr}
            onChange={e => this.onInputChange (fieldname, e)}
          />}
        {type == 4 &&
          <WeaInputNumber ecId={`${this && this.props && this.props.ecId || ''}_WeaInputNumber@xwfj4m`}
            viewAttr={viewAttr}
            value={value}
            onChange={e => this.onInputChange (fieldname, e)}
          />}

      </WeaFormItem>
    );
  };

  getModalHeight=(_height,columns)=>{
    let h = _height*0.6
    if(columns && columns.length>0){
      let itemCountHeight = columns.length*50 + 50
      if(itemCountHeight>h){
        return h
      }else{
        return itemCountHeight
      }

    }else{
      return h
    }

  }

  render () {
    let {planSummaryModal, requestRes, authority, buttonAuth} = this.store;

    let {_height} = this.state
    planSummaryModal = toJS (planSummaryModal);
    requestRes = toJS (requestRes);
    let map = planSummaryModal.type == 'summary'
      ? requestRes.summarymap
      : requestRes.planmap;
    const columns = map ? map.list : [];
    // let {canedit,candel,canreset,canaudit} = authority
    let canedit = buttonAuth.edit;
    let _this = this;
    //更新的临时数据放到state里管理  如果是点击以有的行，不是新增
    if (planSummaryModal.editData.id) {
      this.setState ({formValue: planSummaryModal.editData}, () => {
        _this.store.planSummaryModal.editData = {};
      });
    }

    return (

      <div>
        <Modal ecId={`${this && this.props && this.props.ecId || ''}_Modal@n3gw73`}
          title={planSummaryModal.title}
          visible={planSummaryModal.planSummaryModalVisible}
          maskClosable={false}
          onOk={this.handleOk}
          onCancel={this.handleCancel}
          footer={<div><Button ecId={`${this && this.props && this.props.ecId || ''}_Button@dp37iz`} type="primary" onClick={this.handleOk}>{getLabel('826','确定') }</Button><Button ecId={`${this && this.props && this.props.ecId || ''}_Button@7twl51`}  type="primary" onClick={this.handleCancel}>{getLabel('309','关闭') }</Button></div>}
        >
          <WeaNewScroll ecId={`${this && this.props && this.props.ecId || ''}_WeaNewScroll@01ckr9`} height={this.getModalHeight(_height,columns)}>
            <div className="modal-content">
              <WeaSearchGroup ecId={`${this && this.props && this.props.ecId || ''}_WeaSearchGroup@q6rcv7`} showGroup={true}>
                {columns.map ((v, i) => {
                  return this.getFormItem (
                    v.inputtype,
                    v.showname,
                    this.state.formValue[v.fieldname],
                    canedit ? '2' : '1',
                    v.fieldname,
                    v.ismust,
                    v.ismust2
                  );
                })}
              </WeaSearchGroup>
            </div>
          </WeaNewScroll>

        </Modal>
      </div>
    );
  }
}
